package com.walala.logic.utils;

import com.walala.logic.pojo.ChatMsgBean;
import com.walala.logic.protocol.IMProto;
import com.walala.logic.protocol.ProtocolPackage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProtoMessageUtil {

	private static Logger logger = LoggerFactory.getLogger(ProtoMessageUtil.class);
	
	/**
	 * header编码
	 * @param msg
	 * @return
	 */
	public static byte[] encodeHead(ProtocolPackage msg) {
		ByteBuf buf = Unpooled.buffer(48);
		buf.writeShort(2+48+msg.getProtoBody().length);
		buf.writeShort(msg.getCommand());
		buf.writeLong(msg.getSenderId());
		buf.writeByte(msg.getClientType());
		buf.writeByte(msg.getVersion());
		buf.writeByte(msg.getResult());
		buf.writeLong(msg.getStime());
		buf.writeLong(msg.getReceiverId());
		buf.writeInt(msg.getTraceId());
		buf.writeByte(msg.getAck());
		return buf.array();
	}

	public static ChatMsgBean pbToChatMsgBean(IMProto.ChatMsg pb){
		if(pb == null){
			return null;
		}
		ChatMsgBean bean = new ChatMsgBean();
		bean.setMsgId(pb.getMsgId());
		bean.setMsgType(pb.getMsgType());
		if(StringUtils.isNotBlank(pb.getMsgBody())){
			bean.setMsgBody(pb.getMsgBody());
		}
		bean.setSenderId(pb.getSenderId());
		if(StringUtils.isNotBlank(pb.getSenderName())){
			bean.setSenderName(pb.getSenderName());
		}
		bean.setSessionId(pb.getSessionId());
		bean.setSessionType(pb.getSessionType());
		bean.setTime(pb.getTime());
		if(StringUtils.isNotBlank(pb.getExtra())){
			bean.setExtra(pb.getExtra());
		}
		return bean;
	}

	public static IMProto.ChatMsg chatMsgBeanToPb(ChatMsgBean msg){

		IMProto.ChatMsg.Builder pb = IMProto.ChatMsg.newBuilder();
		pb.setMsgId(msg.getMsgId());
		pb.setMsgType(msg.getMsgType());
		pb.setMsgBody(msg.getMsgBody());
		pb.setSessionType(msg.getSessionType());
		pb.setSessionId(msg.getSessionId());
		pb.setSenderId(msg.getSenderId());
		pb.setSenderName(msg.getSenderName());
		pb.setSeqId(msg.getSeqId());
		pb.setTime(msg.getTime());
		if(StringUtils.isNotBlank(msg.getExtra())){
			pb.setExtra(msg.getExtra());
		}
		return pb.build();

	}

}
